﻿using IntelligentGateway.SmartCommunity.BUS;
using IntelligentGateway.SmartCommunity.DAL;
using IntelligentGateway.SmartCommunity.DevicePlatform;
using IntelligentGateway.SmartCommunity.Model;
using IntelligentGateway.SmartCommunity.Server;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace IntelligentGateway.SmartCommunity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DeviceController : ControllerBase
    {
     
        public CEMSDeviceSerialData cems_serial = DeviceServer.cems_serial;
        public static RaspberryPie pie = DeviceServer.raspberryPie;
        public DeviceController()
        {
        }

        /// <summary>
        /// 设备重启
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("Reboot")]
        public ResponseMessage Reboot()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                pie.RunCommand("reboot");
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "设备查询异常";
            }

            return message;
        }

        /// <summary>
        /// 查询mac地址
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryMac")]
        public ResponseMessage QueryMac()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                message.errcode = 0;
                DeviceBUS deviceBUS = new DeviceBUS();
                message.data = deviceBUS.GetLocalMac();
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询mac地址异常";
            }

            return message;
        }

        /// <summary>
        /// 查询网络信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryNetInfo")]

        public ResponseMessage QueryNetInfo()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                message.errcode = 0;
                message.data = pie.GetJMNetInfo();
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询网络信息异常";
            }

            return message;
        }

        /// <summary>
        /// PING功能
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("PingTest")]
        public ResponseMessage PingTest(string ip)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DeviceBUS bus = new DeviceBUS();
                message.errcode = 0;
                message.data = bus.PingTest(ip);
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "ping异常";
            }

            return message;
        }

        /// <summary>
        /// 修改网络信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateNetInfo")]
        public ResponseMessage UpdateNetInfo(NetInfo netInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string value = string.Empty;
                string[] array = netInfo.Mask.Replace(" ", "").Split('.');
                for (int i = 0; i < array.Length; i++)
                {
                    value += Convert.ToString(Convert.ToInt32(array[i]), 2);
                }
                value = value.PadRight(32, '0');

                string keyWord = "1";
                int index = 0;
                int count = 0;
                while ((index = value.IndexOf(keyWord, index)) != -1)
                {
                    count++;
                    index = index + keyWord.Length;
                }
                netInfo.Mask = count.ToString();

                bool result = pie.UpdateJMNetInfo(netInfo);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "修改失败";
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询网络信息异常";
            }

            return message;
        }

        /// <summary>
        ///更新外呼命令延时时间、是否启用梯控
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateIntervalHeartCheck")]
        public ResponseMessage UpdateIntervalHeartCheck(CemsConfig cemsConfig)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {

                string contentPath = AppDomain.CurrentDomain.BaseDirectory;   //项目根目录
                var filePath = contentPath + "appsettings.json";
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["OutboundInterval"] = cemsConfig.Interval;
                    jsonObject["HeartCheck"] = cemsConfig.HeartCheck;
                    jsonObject["MachineOutbound"] = cemsConfig.MachineOutbound;
                    jsonObject["IndoorOutbound"] = cemsConfig.IndoorOutbound;
                    jsonObject["CarInOutbound"] = cemsConfig.CarInOutbound;
                    jsonObject["MachineAuthorize"] = cemsConfig.MachineAuthorize;
                    jsonObject["IndoorAuthorize"] = cemsConfig.IndoorAuthorize;
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }
                cems_serial.OutboundInterval = cemsConfig.Interval;
                cems_serial.HeartCheck = cemsConfig.HeartCheck;
                cems_serial.MachineOutbound = cemsConfig.MachineOutbound;
                cems_serial.IndoorOutbound = cemsConfig.IndoorOutbound;
                cems_serial.CarInOutbound = cemsConfig.CarInOutbound;
                cems_serial.MachineAuthorize = cemsConfig.MachineAuthorize;
                cems_serial.IndoorAuthorize = cemsConfig.IndoorAuthorize;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "更新异常";
            }

            return message;
        }

        /// <summary>
        ///查询外呼命令延时时间、是否启用梯控
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryCemsConfig")]
        public ResponseMessage QueryCemsConfig()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                CemsConfig cemsConfig = new CemsConfig();
                cemsConfig.Interval = Convert.ToInt32(AppSettingsHelper.Configuration["OutboundInterval"]);
                cemsConfig.HeartCheck = Convert.ToInt32(AppSettingsHelper.Configuration["HeartCheck"]);
                cemsConfig.MachineOutbound = Convert.ToInt32(AppSettingsHelper.Configuration["MachineOutbound"]);
                cemsConfig.IndoorOutbound = Convert.ToInt32(AppSettingsHelper.Configuration["IndoorOutbound"]);
                cemsConfig.CarInOutbound = Convert.ToInt32(AppSettingsHelper.Configuration["CarInOutbound"]);
                cemsConfig.MachineAuthorize = Convert.ToInt32(AppSettingsHelper.Configuration["MachineAuthorize"]);
                cemsConfig.IndoorAuthorize = Convert.ToInt32(AppSettingsHelper.Configuration["IndoorAuthorize"]);

                message.data = cemsConfig;
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询串口信息失败";
            }

            return message;
        }

        /// <summary>
        ///查询串口信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryCemsSerialInfo")]
        public ResponseMessage QueryCemsSerialInfo()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                CemsSerialInfo serialInfo = new CemsSerialInfo();
                serialInfo.BaudRate = AppSettingsHelper.Configuration["BaudRate"];
                serialInfo.Parity = Convert.ToInt32(AppSettingsHelper.Configuration["Parity"]);
                serialInfo.DataBits = Convert.ToInt32(AppSettingsHelper.Configuration["DataBits"]);
                serialInfo.StopBits = Convert.ToInt32(AppSettingsHelper.Configuration["StopBits"]);
                serialInfo.PortName = AppSettingsHelper.Configuration["PortName"];
                message.data = serialInfo;
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询串口信息失败";
            }

            return message;
        }

        /// <summary>
        ///更新串口配置
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateSerialConfig")]
        public ResponseMessage UpdateSerialConfig(CemsSerialInfo cemsSerialInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {

                string contentPath = AppDomain.CurrentDomain.BaseDirectory;   //项目根目录
                var filePath = contentPath + "appsettings.json";
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["BaudRate"] = cemsSerialInfo.BaudRate;
                    jsonObject["Parity"] = cemsSerialInfo.Parity;
                    jsonObject["DataBits"] = cemsSerialInfo.DataBits;
                    jsonObject["StopBits"] = cemsSerialInfo.StopBits;
                    jsonObject["PortName"] = cemsSerialInfo.PortName;
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "更新异常";
            }

            return message;
        }

        /// <summary>
        ///查询人脸面板端口号、CEMS平台地址
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryFacePort")]
        public ResponseMessage QueryFacePort()
        {
            ResponseMessage message = new ResponseMessage();
            PlatformConfig platformConfig = new PlatformConfig();
            try
            {

                platformConfig.FacePort = Convert.ToInt32(AppSettingsHelper.Configuration["FacePort"]);
                platformConfig.CemsPlatformIp = AppSettingsHelper.Configuration["CemsPlatformIp"];
                message.data = platformConfig;
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询串口信息失败";
            }

            return message;
        }

        /// <summary>
        ///更新人脸面板端口号、cems平台地址
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateFacePort")]
        public ResponseMessage UpdateFacePort(PlatformConfig platformConfig)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {

                string contentPath = AppDomain.CurrentDomain.BaseDirectory;   //项目根目录
                var filePath = contentPath + "appsettings.json";
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["FacePort"] = platformConfig.FacePort;
                    jsonObject["CemsPlatformIp"] = platformConfig.CemsPlatformIp;
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "更新异常";
            }

            return message;
        }
    }
}
